<template>
  <div>
    <el-card>
      <template #header>
        <div>
          <el-form :model="form" inline>
            <el-form-item label="关键字">
              <el-input clearable v-model="form.keyWord" placeholder="请输入关键字" style="width: 130px"></el-input>
            </el-form-item>
            <el-form-item label="角色" style="width: 170px">
              <el-select v-model="form.role" placeholder="请选择角色" clearable>
                <el-option label="管理员" value="1" />
                <el-option label="用户" value="2" />
              </el-select>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="addRow()">新增菜单</el-button>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="bindUser()">绑定角色</el-button>
            </el-form-item>
          </el-form>
        </div>
      </template>
      <el-table :data="tableList" border row-key="id" style="height: 61vh">
        <el-table-column prop="id" label="ID" align="center" />
        <el-table-column prop="name" label="名称" align="center" />
        <el-table-column prop="path" label="path" align="center" />
        <el-table-column prop="component" label="组件位置" align="center" />
        <el-table-column label="iCON" align="center">
          <template #default="scope">
            <component :is="scope.row.icon" class="icon" />
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center">
          <template #default="scope">
            <!-- <el-button type="success" link>新增</el-button> -->
            <el-button type="primary" link @click="update(scope.row)">编辑</el-button>
            <el-button type="danger" link @click="delRow(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="card-footer">
        <el-pagination  layout="total, sizes, prev, pager, next, jumper"
        background v-model:page-size="pagination.size"
          v-model:current-page="pagination.page" :total="pagination.total" @size-change="sizeChange"
          @current-change="pageChange" class="pagination" />
      </div>

    </el-card>
    <!--编辑或者新增弹窗-->
    <el-dialog :title="dialogObj.title" v-model="dialogObj.visible" @close="dialogClose" width="70%">
      <span>是否是父级菜单:</span>
      <el-switch @change="switchChange" v-model="value3" inline-prompt active-text="是" inactive-text="否" />
      <el-form :model="dialogForm" label-width="100" ref="formEl" :rules="rules">
        <el-form-item label="名称" prop="name">
          <el-input placeholder="请输入菜单名称" v-model="dialogForm.name"></el-input>
        </el-form-item>
        <el-form-item label="父级菜单" prop="upId">
          <el-select :disabled="value3" v-model="dialogForm.upId" filterable clearable placeholder="请选择父级菜单"
            @change="columnChange">
            <el-option v-for="item in options" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="前端路径" prop="path">
          <el-input placeholder="请输入菜单路径" v-model="dialogForm.path"></el-input>
        </el-form-item>
        <el-form-item label="组件位置" prop="component">
          <el-tooltip class="box-item" effect="dark" content="PS:/admin/memu/memu" placement="top-start">
            <el-input placeholder="请输入组件位置" v-model="dialogForm.component"></el-input>
          </el-tooltip>
        </el-form-item>
        <el-form-item label="icon">
          <icons v-model:icon="dialogForm.icon" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="confirm" type="primary">确定</el-button>
        <el-button @click="dialogObj.visible = false">取消</el-button>
      </template>
    </el-dialog>
    <!-- not finish -->
    <el-dialog :title="bindDialog.title" v-model="bindDialog.visible">
      <el-form :model="bindForm" label-width="100">
        <el-form-item label="选择角色">
          <el-select v-model="bindForm.userId" class="m-2" placeholder="Select" @change="roleChange()">
            <el-option v-for="item in roleOption" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="绑定菜单">
          <el-tree-select v-model="bindForm.routers" :data="treeData" multiple :render-after-expand="false" show-checkbox
            check-strictly check-on-click-node />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="bindingUser" type="primary">确定</el-button>
        <el-button @click="bindDialog.visible = false">取消</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { reactive, ref } from "vue";
import { queryAllroles } from "@/api/admin";
import {
  pageList,
  saveOrUpdate,
  del,
  queryByRoleId,
  roleBinding,
} from "@/api/admin/menu";
import { ElMessage } from "element-plus";
import icons from "@/components/icons/index.vue";

import useStore from "@/store";
import { storeToRefs } from "pinia";

const Store = useStore();
const { memu } = storeToRefs(Store);
const formEl = ref(null);
const value3 = ref(false)
const roleOption = ref([]);
const options = ref([]);

let rules = {
  name: [{ required: true, message: "请输入菜单名称", trigger: "blur" }],
};

let form = reactive({
  keyWord: "",
  role: null,
});

let dialogForm = reactive({
  id: "",
  name: "",
  path: "",
  component: "",
  icon: "",
  upId: ""
});

let dialogObj = reactive({
  title: "",
  visible: false,
  status: "",
});

let bindDialog = reactive({
  title: "",
  visible: false,
  status: "",
});

let pagination = reactive({
  page: 1,
  size: 10,
  total: 0,
});
let bindForm = reactive({
  userId: "",
  routers: "",
});

let tableList = ref([]);

let treeData = ref([]);

const confirm = () => {
  formEl.value.validate((valid, fields) => {
    if (valid) {
      dialogForm.upId = value3 == false ? dialogForm.upId : ""
      saveOrUpdate(dialogForm).then((res) => {
        if (res.status !== 200) {
          ElMessage({
            type: "info",
            message: res.message,
          });
          return;
        }
        ElMessage({
          type: "success",
          message: res.message,
        });
        dialogObj.visible = false;
        getList();
      });
    } else {
      console.log("error submit!", fields);
    }
  });
};

const addRow = () => {
  dialogObj.visible = true;
  dialogObj.title = "添加菜单";
  dialogObj.status = "add";
  dialogForm.id = "";
};

const update = (row) => {
  Object.assign(dialogForm, row);
  dialogObj.title = "编辑菜单";
  dialogObj.status = "updates";
  dialogObj.visible = true;
};

const delRow = (rowData) => {
  ElMessageBox.confirm("删除当前菜单?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(() => {
      del(rowData.id).then((res) => {
        if (res.status !== 200) {
          ElMessage({
            type: "info",
            message: res.message,
          });
          return;
        }
        ElMessage({
          type: "success",
          message: res.message,
        });
        getList();
      });
    })
    .catch(() => {
      /* ElMessage({
                type: "info",
                message: "Delete canceled",
            }); */
    });
};

const sizeChange = (value) => {
  pagination.size = value;
  pagination.page = 1;
  getList();
};

const pageChange = (value) => {
  pagination.page = value;
  getList();
};

const dialogClose = () => {
  dialogForm.name = "";
  dialogForm.path = "";
  dialogForm.icon = "";
  dialogForm.component = "";
};

const getList = (data = {}) => {
  const datas = Object.assign(
    {
      pageNum: pagination.page,
      pageSize: pagination.size,
    },
    { condition: JSON.stringify([]) }
  );
  pageList(datas).then((res) => {
    if (res.status !== 200) {
      ElMessage.error(res.message);
      return;
    }
    tableList.value = res.data.records;
    pagination.page = res.data.currentPage;
    pagination.size = res.data.pageSize;
    pagination.total = res.data.total;
  });
  const pidData = Object.assign(
    {
      pageNum: 1,
      pageSize: 100
    },
    {
      condition: JSON.stringify([
        {
          column: "upId",
          type: "isNull",
          value: "",
        },
        {
          column: "component",
          type: "isNull",
          value: "",
        }
      ])
    }
  )
  pageList(pidData).then((res) => {
    if (res.status == 200) {
      options.value = res.data.records;
    }
  }).catch((msg) => {

  })
  queryAllroles()
    .then((res) => {
      if (res.status == 200) {
        roleOption.value = res.data;
      }
    })
    .catch((msg) => { });
};
const bindUser = () => {
  let memuData = memu.value;
  doTreeData(memuData);
  treeData.value = memuData;
  bindDialog.title = "绑定角色";
  bindDialog.visible = true;
};
const doTreeData = (Data) => {
  for (let i = 0; i < Data.length; i++) {
    Data[i]["value"] = Data[i].id;
    Data[i]["label"] = Data[i].name;
    if (Data[i].children) {
      doTreeData(Data[i].children);
    }
  }
};
const roleChange = () => {
  queryByRoleId({ id: bindForm.userId })
    .then((res) => {
      if (res.status == 200) {
        let temp = [];
        doRouterIds(temp, res.data);
        bindForm.routers = temp;
      }
    })
    .catch((msg) => { });
};

const doRouterIds = (temp, data) => {
  for (let i = 0; i < data.length; i++) {
    temp.push(data[i].id);
    if (data[i].children) {
      doRouterIds(temp, data[i].children);
    }
  }
};
const bindingUser = () => {
  let data = [];
  for (let i = 0; i < bindForm.routers.length; i++) {
    data.push({
      roleId: bindForm.userId,
      routerId: bindForm.routers[i],
    });
  }
  console.log(data);
  roleBinding(data)
    .then((res) => {
      if (res.status == 200) {
        ElMessage.success("更改成功！");
        bindForm = reactive({
          userId: "",
          routers: "",
        });
        bindDialog.visible = false;
      }
    })
    .catch((msg) => { });
};
const switchChange = (value) => {

}
getList();
</script>

<style scoped>
@import url("./index.less");
</style>
